iT邦幫忙

2024 iThome 鐵人賽

DAY 7
0
佛心分享-刷題不只是刷題

C/C++ 刷題30天系列 第 7

Day07__C語言刷LeetCode

  • 分享至 

  • xImage
  •  

21. Merge Two Sorted Lists

You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.

解法1: 用遞迴方式去解決

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
    if (list1 == NULL && list2 == NULL) {return list1;}
    else if (list1 == NULL) {return list2;}
    else if (list2 == NULL) {return list1;}

    if (list1->val < list2->val) {
        list1->next = mergeTwoLists(list1->next, list2);
        return list1;
    }
    else {
        list2->next = mergeTwoLists(list1, list2->next);
        return list2;
    }
}

解法2: 使用指針來解題

# define MIN(a, b) ((a) < (b) ? (a) : (b))

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
    if (list1 == NULL && list2 == NULL) {return list1;}
    else if (list1 == NULL) {return list2;}
    else if (list2 == NULL) {return list1;}

    struct ListNode dummy;
    struct ListNode* current = &dummy;
    dummy.next = NULL;

    while (list1 != NULL && list2 != NULL) {
        if (MIN(list1->val, list2->val) == list1->val) {
            current->next =list1;
            list1 = list1->next;
        }
        else {
            current->next =list2;
            list2 = list2->next;
        }
        current = current->next;
    }

    current->next = (list1 != NULL) ? list1 : list2;
    return dummy.next;
}

1232. Check If It Is a Straight Line

You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.

解法: 外積

bool checkStraightLine(int** coordinates, int coordinatesSize, int* coordinatesColSize) {
    if (coordinatesSize == 2) {
        return true;
    }

    for (int i=0; i < coordinatesSize-2; i++) {
        int x1 = coordinates[i][0];
        int x2 = coordinates[i+1][0];
        int x3 = coordinates[i+2][0];
        int y1 = coordinates[i][1];
        int y2 = coordinates[i+1][1];
        int y3 = coordinates[i+2][1];
        
        if (((x2-x1) * (y3-y1) - (y2-y1) * (x3-x1)) != 0) {
            return false;
        }
    }
    return true;
}

上一篇
Day06__C語言刷LeetCode
下一篇
Day08__C語言刷LeetCode
系列文
C/C++ 刷題30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言